<template>
  <div class="ticket-list-container">
    <div class="table-container">
      <div class="table-header">
        <div class="header-left">
          <el-button type="primary" class="create-btn" @click="handleAddTicket">
            <el-icon class="btn-icon">
              <Plus />
            </el-icon>
            添加股票
          </el-button>
        </div>
        <el-input v-model="search" size="large" placeholder="搜索股票代码..." class="search-input" prefix-icon="Search" />
      </div>

      <el-table :data="filterTableData" style="width: 100%" class="water-drop-table" :header-cell-style="{
        background: 'rgba(236, 245, 255, 0.6)',
        color: '#409EFF',
        fontWeight: 'bold'
      }">
        <el-table-column label="股票代码" prop="symbol" align="center" width="120">
          <template #default="scope">
            <div class="table-cell-content">
              <el-icon class="cell-icon">
                <Document />
              </el-icon>
              <span>{{ scope.row.symbol }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="周期" prop="period" align="center" width="120">
          <template #default="scope">
            <el-tag :type="getPeriodTagType(scope.row.period)" effect="light">
              {{ scope.row.period }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="开始日期" prop="startDate" align="center" width="140">
          <template #default="scope">
            <div class="table-cell-content">
              <el-icon class="cell-icon">
                <Calendar />
              </el-icon>
              <span>{{ scope.row.startDate }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="结束日期" prop="endDate" align="center" width="140">
          <template #default="scope">
            <div class="table-cell-content">
              <el-icon class="cell-icon">
                <Calendar />
              </el-icon>
              <span>{{ scope.row.endDate }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="复权方式" prop="adjust" align="center" width="120">
          <template #default="scope">
            <el-tag :type="getAdjustTagType(scope.row.adjust)">
              {{ getAdjustText(scope.row.adjust) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="超时设置" prop="timeout" align="center" width="120">
          <template #default="scope">
            <span>{{ scope.row.timeout || '默认' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" min-width="200">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" class="action-btn" @click="handleEdit(scope.row)">
                <el-icon>
                  <Edit />
                </el-icon>
                <span>编辑</span>
              </el-button>
              <el-button size="small" type="success" class="action-btn" @click="handleView(scope.row)">
                <el-icon>
                  <View />
                </el-icon>
                <span>查看</span>
              </el-button>
              <el-button size="small" type="danger" class="action-btn" @click="handleDelete(scope.$index, scope.row)">
                <el-icon>
                  <Delete />
                </el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination 
          v-model:current-page="currentPage" 
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="totalTickets"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>

      <div class="empty-placeholder" v-if="filterTableData.length === 0">
        <el-empty description="暂无股票数据" />
      </div>
    </div>

    <!-- 添加/编辑股票对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose">
      <el-form :model="ticketForm" ref="ticketFormRef" :rules="ticketRules" label-width="100px">
        <el-form-item label="股票代码" prop="symbol">
          <el-input v-model="ticketForm.symbol" placeholder="请输入股票代码，如：603777"></el-input>
        </el-form-item>
        <el-form-item label="周期" prop="period">
          <el-select v-model="ticketForm.period" placeholder="请选择周期" style="width: 100%">
            <el-option label="每日" value="daily"></el-option>
            <el-option label="每周" value="weekly"></el-option>
            <el-option label="每月" value="monthly"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker 
            v-model="ticketForm.startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYYMMDD"
            value-format="YYYYMMDD"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker 
            v-model="ticketForm.endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYYMMDD"
            value-format="YYYYMMDD"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="复权方式" prop="adjust">
          <el-radio-group v-model="ticketForm.adjust">
            <el-radio label="">不复权</el-radio>
            <el-radio label="qfq">前复权</el-radio>
            <el-radio label="hfq">后复权</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="超时设置" prop="timeout">
          <el-input v-model.number="ticketForm.timeout" placeholder="请输入超时设置（可选）"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, View, Document, Calendar } from '@element-plus/icons-vue'
import { getAllTickets, addTicket, updateTicket, deleteTicket, type TicketData } from '@/api/ticket-api'

// 表格数据
const ticketList = ref<TicketData[]>([]);
const loading = ref(false);

// 搜索和分页
const search = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalTickets = ref(0);

// 加载Ticket数据
const loadTickets = async () => {
  loading.value = true;
  try {
    const tickets = await getAllTickets();
    ticketList.value = tickets;
    totalTickets.value = tickets.length;
    console.log('Tickets loaded:', tickets);
  } catch (error) {
    console.error('加载Ticket数据失败:', error);
    ElMessage.error('加载Ticket数据失败');
  } finally {
    loading.value = false;
  }
};

// 过滤表格数据
const filterTableData = computed(() => {
  const filtered = ticketList.value.filter(
    (data) => !search.value || data.symbol.toLowerCase().includes(search.value.toLowerCase())
  );
  return filtered;
});

// 表单对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加股票');
const isEdit = ref(false);
const currentId = ref<number | undefined>(undefined);

// 表单数据
const ticketForm = reactive<TicketData>({
  symbol: '',
  period: 'daily',
  startDate: '',
  endDate: '',
  adjust: '',
  timeout: null
});

// 表单验证规则
const ticketRules = {
  symbol: [
    { required: true, message: '请输入股票代码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '股票代码为6位数字', trigger: 'blur' }
  ],
  period: [
    { required: true, message: '请选择周期', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ]
};

// 表单引用
const ticketFormRef = ref();

// 处理周期标签类型
const getPeriodTagType = (period: string) => {
  switch (period) {
    case 'daily': return 'primary';
    case 'weekly': return 'success';
    case 'monthly': return 'warning';
    default: return 'info';
  }
};

// 处理复权方式标签类型
const getAdjustTagType = (adjust: string) => {
  switch (adjust) {
    case 'qfq': return 'success';
    case 'hfq': return 'warning';
    default: return 'info';
  }
};

// 获取复权方式文本
const getAdjustText = (adjust: string) => {
  switch (adjust) {
    case 'qfq': return '前复权';
    case 'hfq': return '后复权';
    default: return '不复权';
  }
};

// 添加股票
const handleAddTicket = () => {
  isEdit.value = false;
  dialogTitle.value = '添加股票';
  dialogVisible.value = true;
  resetForm();
};

// 编辑股票
const handleEdit = (row: TicketData) => {
  isEdit.value = true;
  dialogTitle.value = '编辑股票';
  dialogVisible.value = true;
  currentId.value = row.id;
  
  // 填充表单数据
  Object.assign(ticketForm, {
    symbol: row.symbol,
    period: row.period,
    startDate: row.startDate,
    endDate: row.endDate,
    adjust: row.adjust,
    timeout: row.timeout
  });
};

// 查看详情
const handleView = (row: TicketData) => {
  ElMessage.success(`查看股票 ${row.symbol} 的详细信息`);
  // 这里可以跳转到详情页或弹出详情对话框
};

// 删除确认
const handleDelete = (index: number, row: TicketData) => {
  if (!row.id) {
    ElMessage.warning('无效的记录ID');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除股票 ${row.symbol} 的数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteTicket(row.id as number);
      loadTickets(); // 重新加载数据
      ElMessage.success('删除成功');
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 取消删除操作
  });
};

// 提交表单
const submitForm = async () => {
  if (!ticketFormRef.value) return;
  
  await ticketFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑现有数据
          const updatedTicket = {
            ...ticketForm,
            id: currentId.value
          };
          
          await updateTicket(updatedTicket);
          ElMessage.success('修改成功');
        } else {
          // 添加新数据
          await addTicket(ticketForm);
          ElMessage.success('添加成功');
        }
        
        // 重新加载数据
        loadTickets();
        dialogVisible.value = false;
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error(isEdit.value ? '修改失败' : '添加失败');
      }
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  if (ticketFormRef.value) {
    ticketFormRef.value.resetFields();
  }
  Object.assign(ticketForm, {
    symbol: '',
    period: 'daily',
    startDate: '',
    endDate: '',
    adjust: '',
    timeout: null
  });
  currentId.value = undefined;
};

// 处理对话框关闭
const handleDialogClose = (done: () => void) => {
  resetForm();
  done();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

// 初始化数据
onMounted(() => {
  loadTickets();
});
</script>

<style scoped>
.ticket-list-container {
  padding: 20px;
  margin: 0 auto;
}

.table-container {
  background-color: #f9f9fb;
  border-radius: 10px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(216, 218, 219, 0.15);
  padding: 20px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.table-container::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8) 0%, rgba(245, 247, 250, 0.6) 100%);
  border-radius: 8px;
  z-index: -1;
}

.header-left {
  display: flex;
  align-items: center;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 5px 15px;
  margin-bottom: 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.create-btn {
  border-radius: 20px;
}

.create-btn:hover {
  transform: scale(1.05);
}

.btn-icon {
  font-size: 18px;
  margin-right: 4px;
}

.search-input {
  width: 240px;
  border-radius: 20px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  background: #f9f9fb;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  background: #f0f5fb;
  box-shadow: 0 0 0 1px #409EFF;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409EFF, 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.search-input :deep(.el-input__inner) {
  color: #606266;
}

.water-drop-table {
  margin-top: 16px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.water-drop-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.water-drop-table :deep(.el-table__row:hover) {
  background-color: #f0f7ff !important;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.water-drop-table :deep(td.el-table__cell) {
  border-bottom: 1px solid rgba(235, 238, 245, 0.6);
  padding: 12px 15px;
}

.table-cell-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.cell-icon {
  color: #409EFF;
  font-size: 16px;
  background-color: rgba(236, 245, 255, 0.6);
  padding: 6px;
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  border-radius: 18px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.empty-placeholder {
  height: 200px;
  padding: 40px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-empty {
  padding: 0;
}
</style>